package com.gps.gps

import android.Manifest
import android.app.*
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import kotlinx.coroutines.*

class LocationService : Service() {
    private lateinit var locationManager: LocationManager
    private lateinit var locationListener: LocationListener
    private val serviceScope = CoroutineScope(Dispatchers.IO + Job())
    private var lastUploadTime = 0L
    private var isFirstStart = true
    private var isUpdating = false
    private var lastLocationTime = 0L
    
    companion object {
        private const val NOTIFICATION_ID = 1
        private const val CHANNEL_ID = "LocationServiceChannel"
        private const val UPDATE_INTERVAL = 300000L // 5分钟
    }

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification())
        
        locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
        locationListener = createLocationListener()
        
        // 延迟启动位置更新，等待权限完全生效
        Handler(Looper.getMainLooper()).postDelayed({
            startLocationUpdates()
        }, 2000)
        
        Log.d("LocationService", "服务已创建")
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "Location Service Channel",
                NotificationManager.IMPORTANCE_MIN
            ).apply {
                setShowBadge(false)
                enableLights(false)
                enableVibration(false)
                setSound(null, null)
            }
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }

    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("")
            .setContentText("")
            .setSmallIcon(android.R.drawable.ic_menu_mylocation)
            .setPriority(NotificationCompat.PRIORITY_MIN)
            .setVisibility(NotificationCompat.VISIBILITY_SECRET)
            .setShowWhen(false)
            .setOngoing(true)
            .setSilent(true)
            .build()
    }

    private fun sendLocationToServer(location: Location) {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastLocationTime < 5000) { // 5秒内不重复发送
            Log.d("LocationService", "位置更新太频繁，跳过本次上报")
            return
        }
        lastLocationTime = currentTime

        serviceScope.launch {
            try {
                val deviceId = android.provider.Settings.Secure.getString(
                    contentResolver,
                    android.provider.Settings.Secure.ANDROID_ID
                )
                
                val baseUrl = "https://ha的ip地址/api/map_location/receive"
                val urlString = "$baseUrl?device_id=${URLEncoder.encode(deviceId, "UTF-8")}" +
                              "&name=${URLEncoder.encode(deviceId, "UTF-8")}" +
                              "&latitude=${location.latitude}" +
                              "&longitude=${location.longitude}" +
                              "&accuracy=${location.accuracy}"
                
                Log.d("LocationService", "准备发送请求: $urlString")
                
                val url = URL(urlString)
                val connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "GET"
                connection.connectTimeout = 5000
                connection.readTimeout = 5000
                
                try {
                    val responseCode = connection.responseCode
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        Log.d("LocationService", "位置信息上报成功")
                        stopLocationUpdates()
                        isUpdating = false  // 重置标志位
                        Handler(Looper.getMainLooper()).postDelayed({
                            startLocationUpdates()
                        }, UPDATE_INTERVAL)
                    } else {
                        Log.e("LocationService", "位置信息上报失败: $responseCode")
                        isUpdating = false  // 重置标志位
                        Handler(Looper.getMainLooper()).postDelayed({
                            startLocationUpdates()
                        }, 60000)
                    }
                } finally {
                    connection.disconnect()
                }
            } catch (e: IOException) {
                Log.e("LocationService", "网络请求失败", e)
                isUpdating = false  // 重置标志位
                Handler(Looper.getMainLooper()).postDelayed({
                    startLocationUpdates()
                }, 60000)
            }
        }
    }

    private fun stopLocationUpdates() {
        try {
            locationManager.removeUpdates(locationListener)
            Log.d("LocationService", "已停止位置更新")
        } catch (e: SecurityException) {
            Log.e("LocationService", "停止位置更新失败", e)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("LocationService", "服务onStartCommand被调用")
        if (!isUpdating) {  // 只有在没有更新时才启动
            startLocationUpdates()
        }
        return START_STICKY
    }

    private fun startLocationUpdates() {
        try {
            if (checkLocationPermission()) {
                // 检查是否已经在更新
                if (isUpdating) {
                    Log.d("LocationService", "位置更新已在进行中，跳过")
                    return
                }
                
                isUpdating = true
                Log.d("LocationService", "开始请求位置更新...")
                
                try {
                    locationManager.removeUpdates(locationListener)
                } catch (e: Exception) {
                    Log.e("LocationService", "移除旧的位置更新失败", e)
                }

                // 先尝试GPS定位
                try {
                    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            1000,
                            0f,
                            locationListener,
                            Looper.getMainLooper()
                        )
                        Log.d("LocationService", "GPS位置更新已注册")
                    }
                } catch (e: Exception) {
                    Log.e("LocationService", "注册GPS位置更新失败", e)
                }
                
                // 再尝试网络定位
                try {
                    if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                        locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            1000,
                            0f,
                            locationListener,
                            Looper.getMainLooper()
                        )
                        Log.d("LocationService", "网络位置更新已注册")
                    }
                } catch (e: Exception) {
                    Log.e("LocationService", "注册网络位置更新失败", e)
                }

                // 尝试获取最后已知位置
                try {
                    val lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                        ?: locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
                    
                    lastLocation?.let {
                        Log.d("LocationService", "获取到最后已知位置，精度：${it.accuracy}米")
                        if (it.accuracy <= 100) {
                            sendLocationToServer(it)
                        }
                    }
                } catch (e: Exception) {
                    Log.e("LocationService", "获取最后已知位置失败", e)
                }
            } else {
                Log.e("LocationService", "没有位置权限或GPS未开启")
                startPermissionCheckTimer()
            }
        } catch (e: SecurityException) {
            Log.e("LocationService", "请求位置更新失败", e)
            isUpdating = false
            startPermissionCheckTimer()
        }
    }

    private fun startPermissionCheckTimer() {
        Handler(Looper.getMainLooper()).postDelayed({
            if (checkLocationPermission()) {
                startLocationUpdates()
            }
        }, 5000)
    }

    private fun checkLocationPermission(): Boolean {
        val fineLocation = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED

        val coarseLocation = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED

        val gpsEnabled = try {
            locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        } catch (e: Exception) {
            Log.e("LocationService", "检查GPS状态失败", e)
            false
        }

        Log.d("LocationService", "权限检查 - 精确位置:$fineLocation, 粗略位置:$coarseLocation, GPS:$gpsEnabled")
        
        return fineLocation && coarseLocation && gpsEnabled
    }

    override fun onDestroy() {
        super.onDestroy()
        serviceScope.cancel()
        locationManager.removeUpdates(locationListener)
    }

    override fun onBind(intent: Intent?): IBinder? = null

    private fun createLocationListener(): LocationListener {
        return object : LocationListener {
            override fun onLocationChanged(location: Location) {
                Log.d("LocationService", "收到位置更新，精度：${location.accuracy}米")
                if (location.accuracy <= 100) {
                    Log.d("LocationService", "获取到高精度位置，准备上传")
                    sendLocationToServer(location)
                } else {
                    Log.d("LocationService", "位置精度不足，等待更好的位置信号")
                }
            }

            override fun onProviderEnabled(provider: String) {
                Log.d("LocationService", "位置提供者已启用：$provider")
                startLocationUpdates()
            }

            override fun onProviderDisabled(provider: String) {
                Log.d("LocationService", "位置提供者已禁用：$provider")
            }

            override fun onStatusChanged(provider: String, status: Int, extras: Bundle?) {
                Log.d("LocationService", "位置提供者状态改变：$provider, status: $status")
            }
        }
    }
} 